<template>
  <ComWrapper>
    <el-row justify="space-between">
      <el-col :lg="10">
        <video ref="videoRef" autoplay playsinline id="player" />
      </el-col>
      <el-col :lg="10">
        <canvas ref="canvasRef" width="600px" height="400px" id="canvas" />
      </el-col>
    </el-row>
    
    <div style="margin-top:20px">
      <el-button type="primary" @click="close">关闭摄像头</el-button>
      <el-button type="primary" @click="screenshot">截图图片</el-button>
    </div>
  </ComWrapper>
</template>

<script setup>
import {ref} from 'vue'
import {ElMessage} from 'element-plus'
import {dataURIToFile} from '@/utils/file'

const videoRef = ref(null)
const canvasRef = ref(null)
let mediaStreamTrack

if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
  console.log(navigator)
  ElMessage.warning('该设备暂不支持 getUserMedia')
} else {
  const constraints = {
    video: true,
    audio: false,
  }
  navigator.mediaDevices.getUserMedia(constraints)
    .then(getMediaStream)
    .catch(handleError)
}

// 音视频数据
function getMediaStream(stream) {
  console.log(stream)
  // 获取音视频流轨道，用于停止摄像头
  mediaStreamTrack = typeof stream.stop === 'function' ? stream : stream.getTracks()[0]
  videoRef.value.srcObject = stream
}
// 错误处理
function handleError({name, message}) {
  const errMap = {
    'Requested device not found': '该设备暂时没有摄像头'
  }
  ElMessage.warning(`${name}：${errMap[message]}`)
}
// 截取图像
function screenshot() {
  canvasRef.value.width = 600
  canvasRef.value.height = 400
  const canvasVal = canvasRef.value
  canvasRef.value.getContext('2d').drawImage(videoRef.value, 0, 0, canvasVal.width, canvasVal.height)

  const src = canvasRef.value.toDataURL('image/png')
  const file = dataURIToFile(src, '123')
  ElMessage.success('控制台查看图片路径')
  console.log(src, file)
}
// 关闭摄像头
function close() {
  mediaStreamTrack && mediaStreamTrack.stop()
}
</script>
